package com.mairuide.bill.methodsanalysis.commonaccount;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.mairuide.bill.utils.ExcelUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.base.PageSupport;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.methodsanalysis.CommonStatistics;
import com.mairuide.bill.methodsanalysis.CommonStatisticsParams;
import com.mairuide.bill.methodsanalysis.CommonStatisticsService;
import com.mairuide.bill.utils.ExcelUtil;
import com.mairuide.datalog.ActionType;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.datalog.ModuleFlag;
import com.mairuide.datalog.SystemFlag;
import com.mairuide.entity.PageResult;

/**
 * 共同账户
 * @author mh
 *
 */
@Controller
@RequestMapping("/commonAccount")
public class CommonAccountController extends BaseController {

	@Resource
	private CommonStatisticsService commonStatisticsService;
	@Resource
	private DataOperationLogService dataOperationLogService;

	/**
	 * 常用战法分析共同账户查询入口
	 * 
	 * @param model
	 * @param pagesupport
	 * @return
	 */
	@ModuleCode(pValue = "billskill", value = "commonAccountMC")
	@RequestMapping(value = "/commonAccountInit", method = RequestMethod.GET)
	public Object billcash(ModelMap model, PageSupport pagesupport) {
		model.addAttribute("menu", "commonAccount");
		return "/methodsanalysis/commonAccount";
	}

	/**
	 * 常用战法分析共同账户查询
	 * 
	 * @param model
	 * @param pagesupport
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/getCommonAccount", method = RequestMethod.POST)
	@ResponseBody
	public Object commonAccount(CommonStatisticsParams csp) {
		Map<String, Object> result = new HashMap<String, Object>();
		String caseId = csp.getCaseId();
		if (StringUtils.isNotEmpty(caseId)) {
			if (StringUtils.isNotEmpty(csp.getShowType()) && csp.getShowType().equals("1")) {//列表
				PageResult pr = commonStatisticsService.findCommonAccountByPageEasyUi(csp);
				result.put("rows", pr.getRows());
				result.put("total", pr.getTotal());
			} else if (StringUtils.isNotEmpty(csp.getShowType()) && csp.getShowType().equals("0")) {//柱状图
				List<CommonStatistics> css = commonStatisticsService.findCommonAccountAll(csp);
				if (css != null && !css.isEmpty()) {
					result.put("total", css.size());
					if (css.size() > 10) {
						Collections.sort(css, new SortList());
						List<CommonStatistics> rows = css.subList(0, 10);
						result.put("rows", rows);
					} else {
						result.put("rows", css);
					}
				} else {
					result.put("total", 0);
					result.put("rows", new ArrayList<Object>());
				}
			}

		} else {
			result.put("total", 0);
			result.put("rows", new ArrayList<Object>());
		}
		result.put("showType", csp.getShowType());
		return result;
	}
	
	@RequestMapping(value = "/getCommonAccountD3Init", method = RequestMethod.GET)
	public Object getCommonAccountD3Init(ModelMap model) {
		return "/methodsanalysis/commonAccountD3";
	}
	
	@RequestMapping(value = "/getCommonAccount_d3", method = RequestMethod.POST)
	@ResponseBody
	public Object getCommonAccount_d3(CommonStatisticsParams csp){
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> d3Map = commonStatisticsService.getCommonAccountD3Result(csp);
		result.put("rsd3", d3Map);
		return result;
	}

	@SuppressWarnings("rawtypes")
	class SortList implements Comparator {
		public int compare(Object o1, Object o2) {
			CommonStatistics w1 = (CommonStatistics) o1;
			CommonStatistics w2 = (CommonStatistics) o2;
			return w2.getOccurrences().compareTo(w1.getOccurrences());
		}
	}

	/**
	 * 常用战法分析共同账户详情跳转
	 * 
	 * @param model
	 * @param pagesupport
	 * @return
	 */
	@RequestMapping(value = "/billDetailsGO", method = RequestMethod.GET)
	public Object billDetailsGO(ModelMap model, CommonStatisticsParams csp) {
		model.addAttribute("accountRivalNumber", csp.getAccountRivalNumber());
		model.addAttribute("accountRival", csp.getAccountRival());
		model.addAttribute("ariseDate", csp.getAriseDate());
		model.addAttribute("ariseMoney", csp.getAriseMoney());
		model.addAttribute("organizationNumber", csp.getOrganizationNumber());
		model.addAttribute("organizationName", csp.getOrganizationName());
		model.addAttribute("tellerNumber", csp.getTellerNumber());
		model.addAttribute("caseId", csp.getCaseId());
		return "/methodsanalysis/commonBillDetails";
	}

	/**
	 * 常用战法分析详情
	 * 
	 * @param model
	 * @param pagesupport
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/billDetails")
	@ResponseBody
	public Object billDetails(String sortName, String sortOrder, CommonStatisticsParams csp, PageSupport pagesupport)
			throws ParseException {
		/* 交易对手账号 */
		return commonStatisticsService.findBillDetailsByCaseIdAndAccountRivalNumberEasyUi(csp);
	}

	/**
	 * 共同账户导出
	 * @throws Exception 
	 */
	@RequestMapping(value = "/exportCommonAccount",method = RequestMethod.POST)
	@ResponseBody
	public void exportFile(HttpServletResponse response, CommonStatisticsParams csp) throws Exception {

		// 生成导出excel名称
		Date date = new Date();
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String fileName = "共同账户" + dateFormat.format(date);

		// 设置导出Excel标题
		String[] titles = { "共同账户", "户名", "出现次数", "出现对象", "总金额" };

		// 遍历导出Excel的内容
		List<CommonStatistics> list = commonStatisticsService.findCommonAccountAll(csp);
		List<Map<Integer, String>> lists = new ArrayList<Map<Integer, String>>();
		if (null != list && !list.isEmpty()) {
			for (CommonStatistics cs : list) {
				Map<Integer, String> map = new HashMap<Integer, String>();
				// 共同交易对手账号
				map.put(0, cs.getCommonAccountRivalNumber() == null ? "" : cs.getCommonAccountRivalNumber());
				// 共同交易对手名称
				map.put(1, cs.getCommonAccountRival() == null ? "" : cs.getCommonAccountRival().toString());
				// 交易出现次数
				map.put(2, cs.getOccurrences() == null ? "" : cs.getOccurrences().toString());
				// 出现对象
				map.put(3, cs.getAriseObject() == null ? "" : cs.getAriseObject().toString());
				// 总金额
				map.put(4, cs.getSumMoney() == null ? "" : cs.getSumMoney().toString());
				// 现金
				// 把map集合添加到lists集合
				lists.add(map);
			}
		}

		// 插入导出日志
		dataOperationLogService.save(null, super.getLoginUser(), new DealFlow(), new DealFlow(), SystemFlag.ZD, ModuleFlag.COMMONACCOUNT, ActionType.EXPORT);
		// 把导出的内容写入到流里面
		byte[] content = ExcelUtil.writeExcel(titles, lists);
		InputStream is = new ByteArrayInputStream(content);

		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + ExcelUtils.toUtf8String(fileName+".xls"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null) {
				bis.close();
			}
			if (bos != null) {
				bos.close();
			}
		}
	}

}
